package com.cn.lyl.lawyer.interceptor;

import com.cn.lyl.lawyer.util.CommonResult;

import com.cn.lyl.lawyer.util.Tool;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        System.out.println("拦截器");
        String loginName = httpServletRequest.getParameter("loginName");//前端传递一个登录名

        // 根据登录名去判断session里面是否有值
        String object =  Tool.stringIsNotNull(httpServletRequest.getSession().getAttribute(loginName));
       // String path = httpServletRequest.getServletPath();
//        if(path.startsWith("/back/")||path.startsWith("aa/"))
        if (object == null || !object.equals(loginName)) {

           httpServletResponse.setContentType("text/json;charset=utf-8");
            ObjectMapper mapper = new ObjectMapper();
            String value = mapper.writeValueAsString(CommonResult.unauthorized("未登录"));
            httpServletResponse.getWriter().print(value);
            return false;
        } else {
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
